import { Component, OnInit, Inject, AfterViewChecked, ViewChild } from '@angular/core';
import { NgForm, FormControl } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA , MatDatepickerInputEvent } from '@angular/material';

import { FileService } from '../../service/FileService';
import { ForumService } from '../../service/ForumService';
import { Forum } from '../../models/Forum';
import { environment } from '../../environments/environment';
import { Moment } from 'moment';
import * as moment from 'moment';
import { NewsCategory } from '../../models/NewsCategory';

@Component({
    templateUrl: './editor.html',
    styleUrls: ['./editor.css'],
})
export class EditorComponent implements OnInit, AfterViewChecked {
    messages = {
      forumTitle: '',
      forumContent: '',
      forumType: '',
      forumAuthor: ''
    };
    forum: Forum;
    categorys: NewsCategory[];
    public options: Object = {
        language: 'zh_cn',
        imageUploadURL: environment.apiUrl + 'api/fileupload/img',
        videoUploadURL: '/api/editor',
        fontFamily: {
            'Microsoft YaHei, sans-serif': '微软雅黑',
            'SimHei, sans-serif': '黑体',
            'SimSun, sans-serif': '宋体',
            'KaiTi, sans-serif': '楷体',
            'Arial': 'Arial',
            'Times New Roman,Times, sans-serif': 'Times New Roman'
        },
        fontFamilySelection: true,
        help: false,
        height: 300,
        toolbarButtons: ['bold', 'italic', 'underline', 'strikeThrough', '|',
            'fontFamily', 'fontSize', 'color', '|',
            'paragraphFormat', 'align', 'formatOL', 'formatUL', 'outdent', 'indent', 'quote', '|',
            'insertLink', 'insertImage', 'insertVideo', 'insertTable', '|',
            'emoticons', 'specialCharacters', 'insertHR', 'selectAll', 'clearFormatting', '|',
            'print', 'spellChecker', 'help', 'html', '|', 'undo', 'redo'],
        imageUploadMethod: 'POST',
        events : {
        }
    };

    content: string;
    untouched = true;
    constructor(
        private dialogRef: MatDialogRef<EditorComponent>,
        private fileService: FileService,
        private forumService: ForumService,
        @Inject(MAT_DIALOG_DATA) public data: {forum: Forum, categorys: NewsCategory[]},
    ) {
      this.forum = data.forum ;
      this.categorys = data.categorys;
    }

  @ViewChild('editorForm')
  editorForm: NgForm;
  ngAfterViewChecked() {
    if (this.content) {
      this.untouched = false;
    }
    if (this.editorForm) {
      this.editorForm.valueChanges.subscribe(data => this.checkValidate());
    }
  }
    ngOnInit() {
      this.content = this.forum.content ;
    }

    onSubmit() {
      this.checkValidate(true);
        console.log(this.content);
        this.forum.content = this.content;
        if (this.forum.id !== undefined) {
          this.forumService.updateForum(this.forum).subscribe((res) => {
            this.dialogRef.close(res.res);
          });
        } else {
          this.forumService.addForum(this.forum).subscribe((res) => {
            this.dialogRef.close(res.res);
          });
        }
    }
  checkValidate(isSubmit?: boolean) {
    const form = this.editorForm;

    for (const field in EditorComponent.ErrorMessages) {

      const control = form.controls[field];

      if (control && control.valid) {
        this.messages[field] = '';
      }
      if (control && (control.dirty || isSubmit) && !control.valid) {
        const messages = EditorComponent.ErrorMessages[field];
        if (control.errors) {
          this.messages[field] = messages[Object.keys(control.errors)[0]];
        }
      }

    }
  }

  static ErrorMessages = {
    forumTitle: {
      required: '文章标题不能为空'
    },
    forumContent: {
      required: '文章内容不能为空'
    },
    forumType: {
      required: '文章类型不能为空'
    },
    forumAuthor: {
      required: '文章作者不能为空'
    }
  };

}
